package com.zhiwang.planet.ui.my.withdraw


import android.annotation.SuppressLint
import android.os.Bundle
import android.os.SystemClock
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTRewardVideoAd
import com.uber.autodispose.AutoDispose.autoDisposable
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider
import com.zhiwang.planet.R
import com.zhiwang.planet.aop.net.NetWorkRequired
import com.zhiwang.planet.di.component.DaggerWithDrawComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.BindPayPwdEvent
import com.zhiwang.planet.mvp.p.UserPresenter
import com.zhiwang.planet.mvp.p.UtilPresenter
import com.zhiwang.planet.mvp.p.WithDrawPresenter
import com.zhiwang.planet.mvp.v.UserInfoView
import com.zhiwang.planet.mvp.v.WithDrawDataView
import com.zhiwang.planet.mvp.v.WithDrawView
import com.zhiwang.planet.mvp.v.WxBindCodeInfoView
import com.zhiwang.planet.mvvm.model.entity.User
import com.zhiwang.planet.mvvm.model.entity.main.WithDrawBody
import com.zhiwang.planet.mvvm.model.entity.main.WxBindCodeInfo
import com.zhiwang.planet.ui.BaseFragment
import com.zhiwang.planet.ui.RewardAdInteractionListenerAdapter
import com.zhiwang.planet.ui.RewardVideoAdListenerAdapter
import com.zhiwang.planet.ui.my.WithdrawActivity
import com.zhiwang.planet.util.Toaster
import com.zhiwang.planet.util.androidSchedule
import com.zhiwang.planet.util.quickStartActivity
import com.zhiwang.planet.util.responseFunc
import com.zhiwang.planet.widget.InputPromotionDialog
import com.zhiwang.planet.widget.SimpleDialogBuilder
import kotlinx.android.synthetic.main.fragment_withdraw.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

//微信提现
class WxWithdrawFragment : BaseFragment(), WithDrawView, InputPromotionDialog.Companion.OnPromoteListener, UserInfoView, WithDrawDataView, WxBindCodeInfoView {

    private lateinit var ttAdNative: TTAdNative
    private lateinit var adVideoSlot: AdSlot
    var cashTable: List<String>? = null

    var cash: String = ""

    @Inject
    lateinit var presenter: WithDrawPresenter

    @Inject
    lateinit var userPresenter: UserPresenter

    lateinit var withDrawAdapter: WithDrawAdapter

    @Inject
    lateinit var utilPresenter: UtilPresenter

    private val notBindClickListener = View.OnClickListener {

        if (qrCodeUrl != null)
            WxBindDialog.create(requireContext(), qrCodeUrl!!)
                    .show()
    }

    var isBind: Boolean = false

    var qrCodeUrl: String? = null

    val TAG = "WxWithdrawFragment"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerWithDrawComponent.builder()
                .appComponent(getAppComponent())
                .accountModule(AccountModule(context as AppCompatActivity))
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
        presenter.withdrawView = this
        userPresenter.userInfoView = this
        userPresenter.withdrawDataView = this
        userPresenter.wxBindCodeInfoView = this
        isBind = requireArguments().getBoolean("BIND")

        val width = resources.displayMetrics.widthPixels
        val height = resources.displayMetrics.heightPixels

        adVideoSlot = AdSlot.Builder()
                .setCodeId("931608653")
                .setSupportDeepLink(true)
                .setImageAcceptedSize(width, height)
                .build()
        ttAdNative = TTAdSdk.getAdManager().createAdNative(requireContext())
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_withdraw, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //只需要进页面获取的状态，加载金额列表
        withDrawAdapter = WithDrawAdapter()
        recyclerView.adapter = withDrawAdapter

        if (isBind) {
            addToDiposable(userPresenter.queryUserInfo())
        } else {
            withdraw_account_name.text = getString(R.string.click_bind_wx)
            withdraw_account_name.setOnClickListener(notBindClickListener)
        }

        withdraw_button.setOnClickListener {
            if (isBind.not()) {
                Toaster.message("请先绑定微信")
                return@setOnClickListener
            }
            if (cashTable == null) return@setOnClickListener
            cash = cashTable!![withDrawAdapter.selectPos]

            if ((requireActivity() as WithdrawActivity).checkCashEnough(cash))
                playVideoAndWithDraw()
        }

        val d = userPresenter.getWxWithDrawList()
        addToDiposable(d)
    }

    private fun playVideoAndWithDraw() {


        ttAdNative.loadRewardVideoAd(adVideoSlot, object : RewardVideoAdListenerAdapter() {

            override fun onRewardVideoAdLoad(p0: TTRewardVideoAd?) {

                p0?.setRewardAdInteractionListener(object : RewardAdInteractionListenerAdapter() {

                    var startTime: Long = 0L

                    override fun onRewardVerify(p0: Boolean, p1: Int, p2: String?) {

                    }

                    override fun onVideoComplete() {

                    }

                    override fun onAdShow() {
                        startTime = SystemClock.elapsedRealtime()
                    }

                    override fun onAdClose() {
                        presenter.withdrawWx(cash, "")
                    }

                })

                p0?.showRewardVideoAd(requireActivity())
            }

            override fun onError(p0: Int, p1: String?) {
                presenter.withdrawWx(cash, "")
                p1?.apply {
                    Toaster.message(this)
                }
            }

        })
    }


    override fun onStart() {
        super.onStart()
        if (isBind.not())//如果处于未绑定状态，每次都要加载最新数据
            load()
    }


    private fun load() {
        //获取 微信绑定二维码
        userPresenter.getWxBindCodeInfo()

        //获取最新的绑定信息
        fetchNewestBindState()

    }

    @NetWorkRequired
    override fun onPromote(pwd: String) {
//        cash = cashTable[withDrawAdapter.selectPos]
        if ((context as WithdrawActivity).checkCashEnough(cash)) {
//            presenter.withdrawWx(cash, pwd)
        }
    }

    override fun onWithDraw(body: WithDrawBody) {
        (context as WithdrawActivity).updateDiamond()
        SimpleDialogBuilder()
                .title("申请提现成功")
                .titleTextColor(R.color.colorPrimary)
                .buttonText("我知道了")
                .onButtonClick(View.OnClickListener {
                    quickStartActivity(WithDrawRecordFragment::class.java)
                })
                .content("成功申请提现${body.successNum}元，请耐心等待到账")
                .build(requireContext())
                .show()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBindPayPwd(e: BindPayPwdEvent) {
        hasSetPayPassword = true
    }

    var hasSetPayPassword = false
    override fun onUserInfoLoad(user: User?) {
        hasSetPayPassword = user!!.bindInfo.hasSetPaypassword
//        if (isBind)
//            withdraw_account_name.text = user.bindInfo.weixinNickname
//        if (isBind)
//            withdraw_account_name.setOnClickListener(null)
    }

    override fun onWithDrawListLoad(data: List<String>) {
        cashTable = data
        withDrawAdapter.setDatas(cashTable?.map { it + "元" })

    }

    @SuppressLint("SetTextI18n")
    override fun onLoadWxBindCodeInfo(wxBindCodeInfo: WxBindCodeInfo) {

        qrCodeUrl = wxBindCodeInfo.qrCodeUrl
        bind_help_msg.text = "1.打开微信，点击右上角“+”添加朋友，选择公众号，搜索：${wxBindCodeInfo.officialAccount}，" +
                "并关注该公众号 \n2.进入公众号，发送文字信息：${wxBindCodeInfo.bindCode}，提示绑定成功即可\n\n"
        warm_message.text = getString(R.string.withdraw_warm_message)
    }

    fun fetchNewestBindState() {
        userPresenter.restApi.getIndexData()
                .androidSchedule()
                .responseFunc()
                .map {
                    //更新绑定信息
                    val userDao = userPresenter.userDao
                    val user = userDao.getFirstUser()
//                    user.bindInfo = it.userInfo.bindInfo
                    userDao.updateUser(user)
                    it
                }
                .`as`(autoDisposable(AndroidLifecycleScopeProvider.from(requireActivity())))
                .subscribe {
//                    isBind = it.userInfo.bindInfo.isWeiXinBind
                    userPresenter.queryUserInfo()
                }
    }

}
